package com.xxl.job.executor.service.jobhandler;


import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.config.PayConfig;
import com.xxl.job.executor.entity.Orders;
import com.xxl.job.executor.mapper.OrdersMappper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class TestTask {
    @Autowired
  private  PayConfig payConfig;
    @Autowired
    private OrdersMappper ordersMappper;


    private static Logger logger = LoggerFactory.getLogger(TestTask.class);

    /**
     * 1、简单任务示例（Bean模式）
     */
    @XxlJob("updateOrder")
    public ReturnT<String> demoJobHandler(String param) throws Exception {
        QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
        ordersQueryWrapper.eq("status",0);//查询交易状态为0的,未交易订单
        List<Orders> orders = ordersMappper.selectList(ordersQueryWrapper);//查询
        //        构造client
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        //设置网关地址
        certAlipayRequest.setServerUrl(payConfig.getUrl());
        //设置应用Id
        certAlipayRequest.setAppId(payConfig.getAppid());
        //设置应用私钥
        certAlipayRequest.setPrivateKey(payConfig.getPrivateKey());
        //设置请求格式，固定值json
        certAlipayRequest.setFormat("json");
        //设置字符集
        certAlipayRequest.setCharset("utf-8");
        //设置签名类型
        certAlipayRequest.setSignType("RSA2");
        //设置应用公钥证书路径
        certAlipayRequest.setCertPath(payConfig.getAppCertPath());
        //设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(payConfig.getAlipayCertPath());
        //设置支付宝根证书路径
        certAlipayRequest.setRootCertPath(payConfig.getAlipayRootCertPath());
        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest); //获得初始化的AlipayClient


        for (Orders order : orders) {
            System.out.println(order);
            Map<String, String> map = new HashMap<String, String>();
            map.put("out_trade_no", order.getOrderId());
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();//创建API对应的request类
            request.setBizContent(JSON.toJSONString(map)); //设置业务参数
            AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);
            String buyerLogonId = response.getBuyerLogonId();
            System.out.println(response);
            if (!response.isSuccess()){
                System.out.println(response.getOutTradeNo());
                System.out.println("未支付");
            }else{
                System.out.println(response.getOutTradeNo());
                System.out.println("已支付");
                order.setStatus(1);
                order.setPaymentDate(new Date());
                order.setTradeNo(response.getTradeNo());
                order.setBuyerId(buyerLogonId);
                ordersMappper.updateById(order);
            }
        }
        return ReturnT.SUCCESS;
    }
}
